import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:message_tools/application.dart';

import 'selection_icon.dart';

class FileManager extends StatefulWidget {
  FileManager({@required this.sDCardDir});

  final String sDCardDir;

  @override
  _FileManagerState createState() => _FileManagerState();
}

class _FileManagerState extends State<FileManager> {
  //List<FileSystemEntity> files = [];
  List<FileSystemEntity> tentcentFiles = [];
  MethodChannel _channel = MethodChannel('openFileChannel');
  Directory parentDir;
  Directory currentDir;
  ScrollController controller = ScrollController();
  int count = 0; // 记录当前文件夹中以 . 开头的文件和文件夹
  String sDCardDir;
  List<double> position = [];
  String rootPath;
  var before10Day = DateTime.now().add(Duration(days: -3));

  @override
  void initState() {
    super.initState();
    sDCardDir = widget.sDCardDir;
    parentDir = Directory(sDCardDir);

    rootPath = "$sDCardDir/tencent/MicroMsg/Download";
    currentDir = Directory(rootPath);

    //initDirectory(sDCardDir);
    initTentcentDirectory();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        if (parentDir.path != sDCardDir) {
          initDirectory(parentDir.parent.path);
          jumpToPosition(false);
        } else {
          SystemNavigator.pop();
        }
      },
      child: Scaffold(
          appBar: AppBar(
            title: Text(
              currentDir.path == rootPath
                  ? "选择文件"
                  : (parentDir?.path == sDCardDir
                      ? 'SD Card'
                      : parentDir.path
                          .substring(parentDir.parent.path.length + 1)),
              style: TextStyle(color: Colors.black),
            ),
            elevation: 0.4,
            centerTitle: true,
            backgroundColor: Color(0xffeeeeee),
            leading: currentDir.path == rootPath
                ? IconButton(
                    icon: Icon(
                      Icons.close,
                      color: Colors.black,
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    })
                : IconButton(
                    icon: Icon(
                      Icons.chevron_left,
                      color: Colors.black,
                    ),
                    onPressed: () {
                      debugPrint("parentDir.path = ${parentDir.path} \n");
                      if (currentDir.path == rootPath) {
                        Navigator.pop(context);
                      } else if (parentDir.path == sDCardDir) {
                        initTentcentDirectory();
                      } else {
                        initDirectory(parentDir.parent.path);
                        jumpToPosition(false);
                      }
                    }),
          ),
          backgroundColor: Color(0xfff3f3f3),
          body: Scrollbar(
            child: ListView.builder(
              physics: BouncingScrollPhysics(),
              controller: controller,
              itemCount: tentcentFiles.length != 0 ? tentcentFiles.length : 1,
              itemBuilder: (BuildContext context, int index) {
                if (tentcentFiles.length != 0)
                  return buildListViewItem(tentcentFiles[index]);
                else
                  return Padding(
                    padding: EdgeInsets.only(
                        top: MediaQuery.of(context).size.height / 2 -
                            MediaQuery.of(context).padding.top -
                            56.0),
                    child: Center(
                      child: Text('The folder is empty'),
                    ),
                  );
              },
            ),
          )),
    );
  }

  // 计算文件夹内 文件、文件夹的数量，以 . 开头的除外
  removePointBegin(Directory path) {
    var dir = Directory(path.path).listSync();
    int num = dir.length;

    for (int i = 0; i < dir.length; i++) {
      if (dir[i]
              .path
              .substring(dir[i].parent.path.length + 1)
              .substring(0, 1) ==
          '.') num--;
    }
    return num;
  }

  buildListViewItem(FileSystemEntity file) {
    var isFile = FileSystemEntity.isFileSync(file.path);

    // 去除以 . 开头的文件和文件夹
    if (file.path.substring(file.parent.path.length + 1).substring(0, 1) ==
        '.') {
      count++;
      if (count != tentcentFiles.length) {
        return Container();
      } else {
        return Padding(
          padding: EdgeInsets.only(
              top: MediaQuery.of(context).size.height / 2 -
                  MediaQuery.of(context).padding.top -
                  56.0),
          child: Center(
            child: Text('The folder is empty'),
          ),
        );
      }
    }

    int length = 0;
    if (!isFile) length = removePointBegin(file);

    return InkWell(
      child: Column(
        children: <Widget>[
          ListTile(
            leading: Image.asset(selectIcon(isFile, file)),
            title: Row(
              children: <Widget>[
                Expanded(
                    child: Text(file.path == sDCardDir
                        ? "查看更多文件"
                        : file.path.substring(file.parent.path.length + 1))),
                isFile
                    ? Container()
                    : Text(
                        '$length项',
                        style: TextStyle(color: Colors.grey),
                      )
              ],
            ),
            subtitle: isFile
                ? Text(
                    '${getFileLastModifiedTime(file)}  ${getFileSize(file)}',
                    style: TextStyle(fontSize: 12.0),
                  )
                : null,
            trailing: isFile ? null : Icon(Icons.chevron_right),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 14.0),
            child: Divider(
              height: 1.0,
            ),
          )
        ],
      ),
      onTap: () async {
        if (!isFile) {
          position.insert(position.length, controller.offset);
          initDirectory(file.path);
          jumpToPosition(true);
        } else {
          // openFile(file.path);
          debugPrint("selectFilePath: ${file.path}\n");

          /*Store.value<SmsTaskModel>(context).setSelectFilePath(file.path);
          var readExcelResult = await Flujxl.readExcelOneLine(file.path);
          Store.value<SmsTaskModel>(context)
              .setPreviewSelectContacts(readExcelResult);*/

          Application.setString("_contactFilePath", file.path);
          Navigator.pop(context, file.path);
        }
      },
    );
  }

  void jumpToPosition(bool isEnter) {
    if (isEnter)
      controller.jumpTo(0.0);
    else {
      controller.jumpTo(position[position.length - 1]);
      position.removeLast();
    }
  }

  Future<void> initDirectory(String path) async {
    try {
      setState(() {
        var directory = Directory(path);
        count = 0;
        parentDir = directory;
        currentDir = directory;
        tentcentFiles.clear();
        tentcentFiles = directory.listSync();
      });
    } catch (e) {
      print(e);
      print("Directory does not exist！");
    }
  }

  Future<void> initTentcentDirectory() async {
    try {
      setState(() {
        count = 0;
        tentcentFiles.clear();
        var filePaths = ["/tencent/MicroMsg/Download", "/tencent/QQfile_recv"];
        filePaths.forEach((path) {
          initMyDirectors("$sDCardDir$path");
        });

        var directory = Directory("$sDCardDir/tencent/MicroMsg/Download");
        var sdCard = Directory.fromUri(Uri.file(sDCardDir));
        tentcentFiles.add(sdCard);

        setState(() {
          currentDir = directory;
        });
      });
    } catch (e) {
      print(e);
      print("Directory does not exist！");
    }
  }

  initMyDirectors(String filePath) {
    var directory = Directory(filePath);
    var fileList = directory.listSync();
    fileList.forEach((f) {
      var isFile = FileSystemEntity.isFileSync(f.path);
      if (isFile) {
        DateTime time = File(f.resolveSymbolicLinksSync()).lastModifiedSync();
        if (time.isAfter(before10Day)) {
          tentcentFiles.add(f);
        }
      }
    });

    tentcentFiles.sort((left, right) {
      DateTime leftTime =
          File(left.resolveSymbolicLinksSync()).lastModifiedSync();

      DateTime rightTime =
          File(right.resolveSymbolicLinksSync()).lastModifiedSync();
      return rightTime.compareTo(leftTime);
    });
  }

  getFileSize(FileSystemEntity file) {
    int fileSize = File(file.resolveSymbolicLinksSync()).lengthSync();
    if (fileSize < 1024) {
      // b
      return '${fileSize.toStringAsFixed(2)}B';
    } else if (1024 <= fileSize && fileSize < 1048576) {
      // kb
      return '${(fileSize / 1024).toStringAsFixed(2)}KB';
    } else if (1048576 <= fileSize && fileSize < 1073741824) {
      // mb
      return '${(fileSize / 1024 / 1024).toStringAsFixed(2)}MB';
    }
  }

  getFileLastModifiedTime(FileSystemEntity file) {
    DateTime dateTime =
        File(file.resolveSymbolicLinksSync()).lastModifiedSync();

    String time =
        '${dateTime.year}-${dateTime.month < 10 ? 0 : ''}${dateTime.month}-${dateTime.day < 10 ? 0 : ''}${dateTime.day} ${dateTime.hour < 10 ? 0 : ''}${dateTime.hour}:${dateTime.minute < 10 ? 0 : ''}${dateTime.minute}';
    return time;
  }

  openFile(String path) {
    final Map<String, dynamic> args = <String, dynamic>{'path': path};
    _channel.invokeMethod('openFile', args);
  }
}
